package cn.lhf.myblog.controller;

import cn.lhf.myblog.context.StatusCode;
import cn.lhf.myblog.exception.EmailExisted;
import cn.lhf.myblog.exception.UserNameExisted;
import cn.lhf.myblog.http.requst.user.RegisterForm;
import cn.lhf.myblog.db.entity.User;
import cn.lhf.myblog.http.result.Result;
import cn.lhf.myblog.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/register")
    public Result onRegister(RegisterForm form) {
        Result result = new Result();
        if (!form.isForm()) {
            result.setCode(StatusCode.UNKNOWN);
            return result;
        }
        if (!form.getPassword().equals(form.getPassword2())) {

            return result;
        }

        try {
            User user = userService.register(form.to());
            user.setPassword(null);
            result.setInfo(user);
        } catch (UserNameExisted userNameExisted) {
            userNameExisted.printStackTrace();
            result.setCode(StatusCode.USERNAME_EXISTED);
            result.setMsg("用户名已存在");
        } catch (EmailExisted emailExisted) {
            emailExisted.printStackTrace();
            result.setCode(StatusCode.EMAIL_EXISTED);
            result.setMsg("邮箱地址已存在");
        }
        return result;
    }

    @PostMapping("/login")
    public Result onLogin() {
        Result result = new Result();

        return result;
    }

}
